import { defineStore } from "pinia";
import { RouteRecordRaw } from "vue-router";
import { getAllFunctionsTreeByAppId } from "/@/api/aiot/menu";
import { FuncitonTypeName, FunctionType, MenuItem, MenuType, PartialMenuItem } from "/@/api/aiot/menu/models";
import { useI18n } from "/@/locales/useI18n";
import router from "/@/router";
import { firstCharToUpper } from "/@/utils/common";
import { useUserStore } from "./user";
import { RequsetOptons } from "/@/api/req";
import { loopItem } from "/@/utils/treeData";

export interface ParamRouteInfo {
  name: string;
  paramKey: string;
  paramValue: string;
}
//如果路由含参数，则对应两种路由，一种带参，一种不带
//所有有参数的路由对应的菜单functionUrl字段值
enum FunctionUrlWithParam {
  messageCenter = "messageCenter",
}

//参数路由对应的路由名字和参数key对象
const FunctionUrlWithParamRouteInfo: Record<FunctionUrlWithParam, ParamRouteInfo> = {
  [FunctionUrlWithParam.messageCenter]: {
    name: "messageCenter-activeKey",
    paramKey: "activeKey",
    paramValue: "",
  },
};

//部分页面路由与页面组件路径映射关系
const pageUrlPath = {
  Tenant: "Tenant/Tenant",
  ProjectManage: "ProjectManage/ProjectManage",
  ProjectView: "ProjectView/ProjectView",
  Group: "Group/Group",
  Account: "Account/Account",
  CustomerManage: "CustomerManage/CustomerManage",
  Unit: "Unit/Unit",
  WorkOrderOverview: "WorkOrderOverview/WorkOrderOverview",
  MessageCenter: "MessageCenter/MessageCenter",
  AlarmCenter: "AlarmCenter/AlarmCenter", // 告警中心
  ProjectCenter: "ProjectCenter/ProjectCenter", // 项目中心
  EquipmentCenter: "EquipmentCenter/EquipmentCenter",
  ProductCenter: "ProductCenter/ProductCenter",
  ProductModel: "ProductModel/ProductModel",
  ProductType: "ProductType/ProductType",
  ProductUpgrade: "ProductUpgrade/ProductUpgrade",
  AlarmStrategy: "AlarmStrategy/AlarmStrategy", // 告警策略
  EquipmentModel: "EquipmentModel/EquipmentModel", // 设备机型
  //菜单的functionUrl字段值作为路由名称必须唯一
  // PlatformDeviceType: "DeviceType",
};
function getPageComponentPath(pageUrl: string) {
  pageUrl = firstCharToUpper(pageUrl);
  return pageUrlPath[pageUrl] || pageUrl;
}

// function get404Page() {
//   return () => import("../../views/404.vue");
// }

const dynamicModules = import.meta.glob("../../views/**/*.vue");

function handleMenuItem(routeData: RouteRecordRaw[], rootRouteName: string, item: MenuItem, parentItems: MenuItem[]) {
  const { t } = useI18n();
  item.title = t(`routes.${item.name}`);
  if (
    item.functionUrl.startsWith("http") /*iframe菜单*/ ||
    item.functionUrl.startsWith("/") /* 根路由页面 如设备详情、项目详情，已写死路由数据不需动态添加 */
  ) {
    item.action = item.functionUrl;
    return;
  }
  if (router.hasRoute(item.functionUrl)) {
    //平台级和企业级有重复的菜单 返回false 移除该重复的菜单
    return false;
  }
  item._children = item.children;
  if (item.children && item.children.length > 0 && item.type === MenuType.FEATURE) {
    item.action = item.functionUrl;
    parentItems.push(item);
    const removeIds: string[] = [];
    item.children.forEach((el) => {
      const re = handleMenuItem(routeData, rootRouteName, el, parentItems);
      if (re === false) {
        removeIds.push(el.functionId);
      }
    });
    removeItems(item.children, removeIds);
  } else {
    delete item.children;
    let parentActions: string[] = [rootRouteName].concat(parentItems.map((el) => el.functionUrl as string));
    const route: RouteRecordRaw = {
      path: `/${parentActions.join("/")}/${item.functionUrl}`,
      name: item.functionUrl,
      component:
        dynamicModules[
          `../../views/${rootRouteName}/${FuncitonTypeName[item.functionType]}/${getPageComponentPath(
            item.functionUrl
          )}.vue`
        ],
    };
    item.action = route.path;
    //动态加入路由数据
    router.addRoute(rootRouteName, route);
    routeData.push(route);
    if (item.functionUrl === FunctionUrlWithParam.messageCenter) {
      //消息中心还需一个额外的参数路由 跳转到对应tab
      const copyRoute = Object.assign({}, route);
      const paramRouteInfo = FunctionUrlWithParamRouteInfo[FunctionUrlWithParam.messageCenter];
      copyRoute.path += `/:${paramRouteInfo.paramKey}`;
      copyRoute.name = paramRouteInfo.name;
      copyRoute.component =
        dynamicModules[
          `../../views/${rootRouteName}/${FuncitonTypeName[item.functionType]}/${getPageComponentPath(
            item.functionUrl
          )}.vue`
        ];
      router.addRoute(rootRouteName, copyRoute);
      routeData.push(copyRoute);
    }
  }
}

export function handleMenuSort(menuData?: MenuItem[]) {
  if (menuData && menuData.length > 0) {
    menuData.sort((a, b) => {
      return a.sortValue - b.sortValue;
    });
    menuData.forEach((menuItem) => {
      handleMenuSort(menuItem.children);
    });
  }
}

function removeItems(data: MenuItem[], ids: string[]) {
  ids.forEach((id) => {
    const index = data.findIndex((el) => el.functionId === id);
    index >= 0 && data.splice(index, 1);
  });
}

export const useMenuStore = defineStore("menu", {
  state: (): { menuData: MenuItem[] } => {
    return {
      //菜单数据
      menuData: [],
    };
  },
  actions: {
    /**
     * 初始化菜单和路由
     * 将菜单转化为路由数据 并加入到vueRouter中
     */
    async initAuthMenu({ rootRouteName, appId }: { rootRouteName: string; appId: string }) {
      //先加载用户数据，获取用户角色
      const userStore = useUserStore();
      const options: RequsetOptons = {
        useGlobalLoading: false,
        useDefaultErrHandle: false,
        useDefaultFailHandle: false,
        autoRedirect: false,
      };
      const re = await userStore.reloadCurUserDetail(options);
      if (!re) return null;
      const menuData = await getAllFunctionsTreeByAppId({ appId }, options);
      if (!menuData) return null;
      if (userStore.isPlatformUser()) {
        //平台端用户需把企业端的菜单去掉
        for (let i = menuData.length - 1; i >= 0; i--) {
          if (menuData[i].functionType === FunctionType.ENTERPRISE) {
            menuData.splice(i, 1);
          }
        }
      }
      const routeData: RouteRecordRaw[] = [];
      handleMenuSort(menuData);
      const removeIds: string[] = [];
      menuData.forEach((el, i) => {
        const re = handleMenuItem(routeData, rootRouteName, el, []);
        if (re === false) {
          removeIds.push(el.functionId);
        }
      });
      removeItems(menuData, removeIds);
      this.menuData = menuData;
      //菜单目前只有两级
      //第一层是模块或功能页面
      //第二层是功能页面
      return { routeData };
    },
    /**
     * 根据带参数路由的path，获取其参数路由的信息
     * /aiot/message/messageCenter/plateform => /aiot/message/messageCenter
     */
    handleParamPath(path) {
      if (path.indexOf(`/${FunctionUrlWithParam.messageCenter}/`) !== -1) {
        // /aiot/message/messageCenter/xxxx
        const target = FunctionUrlWithParamRouteInfo[FunctionUrlWithParam.messageCenter];
        const arr = path.split("/");
        target.paramValue = arr[arr.length - 1];
        return target;
      }
      return null;
    },
    getProjectMenuData(): MenuItem[] {
      let target: MenuItem | null = null;
      loopItem(this.menuData, (item) => {
        if (item.functionUrl === "/projectDetail") {
          target = item;
          return false;
        }
      });
      return target ? (target as MenuItem).children || [] : [];
    },
  },
});
